package com.eway.viewanimator;

import android.animation.ObjectAnimator;
import android.animation.TypeEvaluator;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

public class Object_Animator_activity extends AppCompatActivity implements View.OnClickListener {

	private TextView showObj;

	private ImageView circleImg;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_object__animator_activity);

		findViewById(R.id.object_animator_start).setOnClickListener(this);
		showObj = findViewById(R.id.show_obj_animator);

		circleImg = findViewById(R.id.object_circle);

		findViewById(R.id.custom_object_animator).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.object_animator_start:
				initObjectAnimator();
				break;

			case R.id.custom_object_animator:
				initCustomAnimator();
				break;
			default:
				break;
		}
	}


	private void initObjectAnimator() {
		ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(showObj, "scaleX", 1, 3, 1);
		objectAnimator.setDuration(1000);
		objectAnimator.start();
	}


	private void initCustomAnimator() {

		ObjectAnimator objectAnimator = ObjectAnimator.ofObject(circleImg, "method",
				new CustomObjEvolation(), new Point(circleImg.getLeft(), circleImg.getTop()),
				new Point(circleImg.getLeft() + 200, circleImg.getTop() + 300));

		objectAnimator.setDuration(2000);
		objectAnimator.setInterpolator(new LinearInterpolator());
		objectAnimator.start();
	}

	private class CustomObjEvolation implements TypeEvaluator<Point> {

		@Override
		public Point evaluate(float fraction, Point startValue, Point endValue) {
			int startX = startValue.x;
			int startY = startValue.y;
			int endX = endValue.x;
			int endY = endValue.y;

			int currentX = (int) (startX + fraction * (endX - startX));
			int currentY;

			if (fraction * 2 <= 1) {
				currentY = (int) (startY + fraction * 2 * (endY - startY));
			} else {
				currentY = endY;
			}

			return new Point(currentX, currentY);
		}
	}
}
